package com.wu.server.service;

import com.wu.server.Thread.MainThread;
import com.wu.server.code.Code;
import com.wu.server.dao.NewShopsRepository;
import com.wu.server.entity.Goods;
import com.wu.server.entity.Shop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class ShopServer {
    @Autowired
    Code code;
    @Autowired
    NewShopsRepository shopsRepository;
    @Autowired
    ShopTopServer shopTopServer;
    public Object queryShop(String shopId, String shopName, String salesRange, String order,String sort, int pageNum, int pageSize) {
        String shopNameQuery = "%" + shopName + "%";
        String shopIdQuery = !shopId.equals("") ? shopId : null;
        String[] salesRangeQuery = salesRange.split(",");//价格区间
        Pageable pageable = PageRequest.of(pageNum - 1,pageSize, Sort.Direction.fromString(order),sort);
        Page<Shop> shop =  shopsRepository.findAllBy(shopIdQuery, shopNameQuery, salesRangeQuery[0],salesRangeQuery[1], pageable);
        List<Shop> data = shop.getContent();
        HashMap<String,Object> paging = new HashMap<>();
        paging.put("total",shop.getTotalElements());
        paging.put("pageNum",shop.getNumber()+1);
        paging.put("pageSize",shop.getSize());
        HashMap<String,Object> result = new HashMap<>();
        result.put("paging",paging);
        result.put("data",data);
        return code.getMeta(Code.SUCCESS,result);
    }
    public Object insertShop(Shop shop) {
        try {
            shopsRepository.save(shop);
            shopTopServer.sendData();
            return code.getMeta(Code.SUCCESS,shop);
        }catch (Exception e){
            return code.getMeta(Code.creatFail,null);
        }
    }
    public Object updateShop(Shop shop) {
        try {
            shopsRepository.save(shop);
            shopTopServer.sendData();
            return code.getMeta(Code.SUCCESS,shop);
        }catch (Exception e){
            return code.getMeta(Code.updateFail,null);
        }
    }
    public Object deleteShop(int id) {
        try {
            shopsRepository.deleteShopById(id);
            shopTopServer.sendData();
            return code.getMeta(Code.SUCCESS,null);
        }catch (Exception e){
            return code.getMeta(Code.deleteFail,null);
        }
    }
}
